import 'dart:io';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/cupertino.dart';
import 'package:fwanandroid/model/api/interceptors/RequestInterceptors.dart';
import 'package:fwanandroid/model/bean/ApiResponse.dart';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

import 'interceptors/ErrorInterceptor.dart';

/**
 * 参考
 * https://front-end.toimc.com/notes-page/project/community-flutter/09-%E5%B0%81%E8%A3%85%E8%AF%B7%E6%B1%82.html#%E4%B8%8A%E4%BC%A0%E6%96%87%E4%BB%B6
 */
class DioClient {
  static final DioClient _instance = DioClient._internal();

  factory DioClient() => _instance;

  DioClient._internal() {}

  late Dio _dio;
  CancelToken _cancelToken = CancelToken();

  Future init() async {
    // 初始化选项
    var options = BaseOptions(
        baseUrl: "https://www.wanandroid.com/",
        connectTimeout: const Duration(seconds: 5),
        receiveTimeout: const Duration(seconds: 5));
    Directory tempDir = await getTemporaryDirectory();
    _dio = Dio(options)

      // cookie处理
      ..interceptors.add(CookieManager(PersistCookieJar(
          ignoreExpires: true, storage: FileStorage(tempDir.path))))
    // 日志打印
      ..interceptors.add(PrettyDioLogger(
          requestHeader: true,
          requestBody: true,
          responseHeader: true,
          responseBody: true))
      // 异常处理
      ..interceptors.add(ErrorInterceptor());

  }

  // 取消请求
  void cancelRequests({CancelToken? cancelToken}) {
    cancelToken ?? _cancelToken.cancel('Request Canceled');
    cancelToken?.cancel('Request Canceled');
  }

  Future<ApiResponse> get(String url, Map<String, dynamic>? params,
      Options? options, CancelToken? cancelToken) async {
    Response response = await _dio.get(url,
        queryParameters: params,
        options: options ?? Options(),
        cancelToken: cancelToken ?? _cancelToken);
    return ApiResponse.createApiResponse(response);
  }

  Future<ApiResponse> post(String url, dynamic data, Options? options,
      CancelToken? cancelToken) async {
    Response response = await _dio.post(url,
        data: data ?? {},
        options: options ?? Options(),
        cancelToken: cancelToken ?? _cancelToken);
    return ApiResponse.createApiResponse(response);
  }
}
